package com.yindian.cos.easy.security.authentication.login.normal.smsCode;

import com.yindian.cos.easy.security.authentication.login.normal.AbstractLoginAuthentication;
import com.yindian.cos.easy.security.exception.NullMobileException;
import com.yindian.cos.easy.security.exception.NullSmsCodeException;
import com.yindian.cos.easy.security.properties.EasySecurityProperties;
import com.yindian.cos.easy.security.properties.SmsCodeLoginProperties;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 短信验证码登录拦截器
 *
 * @author zhangchuanhao
 * @create 2018/11/18
 */
@Log4j2
public class SmsCodeLoginLoginAuthentication extends AbstractLoginAuthentication {

    private final SmsCodeLoginProperties smsCodeLoginProperties;

    private final String loginUrl;

    private final String method;

    private final String mobileParameterName;

    private final String smsCodeParameterName;

    public SmsCodeLoginLoginAuthentication(EasySecurityProperties easySecurityProperties, SmsCodeLoginUserService userService) {
        super(userService);
        this.smsCodeLoginProperties = easySecurityProperties.getSmsCode();
        this.loginUrl = smsCodeLoginProperties.getLoginUrl();
        this.method = smsCodeLoginProperties.getMethod();
        this.mobileParameterName = smsCodeLoginProperties.getMobileParameterName();
        this.smsCodeParameterName = smsCodeLoginProperties.getSmsCodeParameterName();
    }

    @Override
    public boolean support(HttpServletRequest request) {
        String requestUrl = request.getRequestURI();
        String requestMethod = request.getMethod();
        // 验证地址是否匹配
        if (loginUrl.equals(requestUrl)) {
            // 验证方法是否匹配
            if (StringUtils.equalsIgnoreCase(method, requestMethod)) {
                log.debug("执行拦截过滤器{}", this.getClass().getSimpleName());
                // 验证手机号
                String mobile = request.getParameter(mobileParameterName);
                if (StringUtils.isBlank(mobile)) {
                    throw new NullMobileException("短信验证码登录手机号不能为空");
                }
                // 验证验证码
                String smsCode = request.getParameter(smsCodeParameterName);
                if (StringUtils.isBlank(smsCode)) {
                    throw new NullSmsCodeException("短信验证码登录验证码不能为空");
                }
                return true;
            }
        }
        return false;
    }

    @Override
    public int order() {
        return smsCodeLoginProperties.getOrder();
    }
}
